package adb;

import static adb.ADBView.adbVariable;
import static adb.ADBView.jLabelBatteryValue;
import static adb.ADBView.jLabelCPUValue;
import static adb.ADBView.jLabelClearData;
import static adb.ADBView.jLabelCloseApp;
import static adb.ADBView.jLabelInstallAPK;
import static adb.ADBView.jLabelListApps;
import static adb.ADBView.jLabelOSK;
import static adb.ADBView.jLabelRAMvalue;
import static adb.ADBView.jLabelRunApp;
import static adb.ADBView.jLabelScreenShot;
import static adb.ADBView.jLabelSdcard0Value;
import static adb.ADBView.jLabelSdcard1Value;
import static adb.ADBView.jLabelSignalValue;
import static adb.ADBView.jLabelTempValue;
import static adb.ADBView.jLabelToLeft;
import static adb.ADBView.jLabelToRight;
import static adb.ADBView.jLabelUninstall;
import static adb.ADBView.jScrollPaneDevice;
import static adb.ADBView.jTextFieldFilter;
import static adb.ADBView.jTreeDevice;
import com.android.ddmlib.AndroidDebugBridge;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import javax.swing.SwingWorker;
import javax.swing.tree.DefaultMutableTreeNode;

public class LoadingInBackground extends SwingWorker<Void, String>{

    int connect = 0;

    @Override
    protected Void doInBackground() throws Exception {
        
        AndroidDebugBridge.init(false /* debugger support */);
        AndroidDebugBridge bridge = AndroidDebugBridge.createBridge();
        while (bridge.hasInitialDeviceList() == false) {
                try {
                    Thread.sleep(2000);
                    } catch (InterruptedException e) {}
            }
        connect=1;
        String linebyline="";
        String battery = adbVariable +" shell dumpsys battery";
        String signal = adbVariable +" shell dumpsys telephony.registry";
        String CPU = adbVariable +" shell dumpsys cpuinfo";
        String SDcard = adbVariable +" shell df";
        String Ram = adbVariable +" shell dumpsys meminfo";
        
        
        while(true){Thread.sleep(1000);
//        if(bridge.hasInitialDeviceList() == false)
//        {
//            jTreeDevice.setModel(null);
//        }else {
//            
//        }
        //battery
        BufferedReader batteryBR=runCmd(battery);
        String out="";
        while ((linebyline = batteryBR.readLine()) != null) {
                    if (linebyline.contains("level:")) {out=linebyline;} 
        }
        if(out.length()>9){        
            jLabelBatteryValue.setText(out.substring(9));
            //loading JtreeDevice
            if(bridge.hasInitialDeviceList() == false){
                loadTreeFileDevice b = new loadTreeFileDevice();
                b.execute();
                connect=1;
                
                //System.out.print("false\n");
            }
            if(bridge.hasInitialDeviceList() == true &&connect==0) {
                loadTreeFileDevice b = new loadTreeFileDevice();
                b.execute();
                
                jLabelToLeft.setVisible(true);
                jLabelToRight.setVisible(true);
                jLabelInstallAPK.setVisible(true);
                jLabelScreenShot.setVisible(true);
                jLabelOSK.setVisible(true);
                jLabelListApps.setVisible(true);
                
                connect=1;
                //System.out.print("true\n");
            }
        }
        else {  jLabelBatteryValue.setText("");
        
        DefaultMutableTreeNode treeNode1 = new DefaultMutableTreeNode("root");
        DefaultMutableTreeNode treeNode2 = new DefaultMutableTreeNode("Check connection");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Check Driver");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Click button Check");
        treeNode1.add(treeNode2);
        treeNode2 = new javax.swing.tree.DefaultMutableTreeNode("Exit and try again");
        treeNode1.add(treeNode2);
        jTreeDevice.setModel(new javax.swing.tree.DefaultTreeModel(treeNode1));
        connect=0;
                jLabelToLeft.setVisible(false);
                jLabelToRight.setVisible(false);
                jLabelInstallAPK.setVisible(false);
                jLabelScreenShot.setVisible(false);
                jLabelOSK.setVisible(false);
                jLabelListApps.setVisible(false);
                jLabelUninstall.setVisible(false);
                jLabelRunApp.setVisible(false);
                jLabelCloseApp.setVisible(false);
                jLabelClearData.setVisible(false);
                
                jTextFieldFilter.setEnabled(false);
                
                jTreeDevice.setVisible(true);
                jTreeDevice.setEnabled(true);
                jScrollPaneDevice.setViewportView(jTreeDevice);
        }
        //temperature
        BufferedReader temp=runCmd(battery);
        while ((linebyline = temp.readLine()) != null) {
                    if (linebyline.contains("temperature:")) {out=linebyline;}
        }
        if(out.length()>14) {
            jLabelTempValue.setText(out.substring(14));}
        else     jLabelTempValue.setText("");
        //CPU
        BufferedReader CPUBR=runCmd(CPU);

        while ((linebyline = CPUBR.readLine()) != null) {
                    if (linebyline.contains("TOTAL:")){out=linebyline;} 
        }
        if(out.length()>1)        jLabelCPUValue.setText(out.substring(0,out.indexOf("TOTAL:")-1));
        else     jLabelCPUValue.setText("");
        BufferedReader Signal=runCmd(signal);

        while ((linebyline = Signal.readLine()) != null) {
                    if (linebyline.contains("mSignalStrength=SignalStrength:")) {out=linebyline;}
        }
        if(out.length()>1)       { jLabelSignalValue.setText(out.substring(34,36));}
        else    { jLabelSignalValue.setText("");}
        BufferedReader SDCard0=runCmd(SDcard);
        BufferedReader SDCard1=SDCard0;
        String TotalSD0 = "";
        String UsedSD0="";
        int OK=0;
        while ((linebyline = SDCard0.readLine()) != null&&OK==0) {
            
                    if (linebyline.contains("sdcard")) {
                        TotalSD0=linebyline;OK=1;
                    }
        }
        if(TotalSD0.length()>2){
            TotalSD0=TotalSD0.replaceAll(" ", "-");
            TotalSD0=TotalSD0.replaceAll("--", "-");
            TotalSD0=TotalSD0.replaceAll("--", "-");
            TotalSD0=TotalSD0.replaceAll("--", "-");
            TotalSD0=TotalSD0.replaceAll("--", "-");
            TotalSD0=TotalSD0.replaceAll("--", "-");
            TotalSD0=TotalSD0.replaceAll("--", "-");
            String[] sd = TotalSD0.split("-");
            TotalSD0 = sd[1];
            UsedSD0=sd[2];
            jLabelSdcard0Value.setText(UsedSD0+"/"+TotalSD0);
        }else jLabelSdcard0Value.setText("");
        String TotalSD1 = "";
        String UsedSD1="";
        int OK1=0;
        while ((linebyline = SDCard1.readLine()) != null&&OK1==0) {
                    if (linebyline.contains("sdcard1")) {
                        TotalSD1=linebyline;OK1=1;
                    }
        }
        //System.out.print("TotalSD1="+TotalSD1+"\n");
        if(TotalSD1.length()>2){
            TotalSD1=TotalSD1.replaceAll(" ", "-");
            TotalSD1=TotalSD1.replaceAll("--", "-");
            TotalSD1=TotalSD1.replaceAll("--", "-");
            TotalSD1=TotalSD1.replaceAll("--", "-");
            TotalSD1=TotalSD1.replaceAll("--", "-");
            TotalSD1=TotalSD1.replaceAll("--", "-");
            TotalSD1=TotalSD1.replaceAll("--", "-");
            String[] sd = TotalSD1.split("-");
            TotalSD1 = sd[1];
            UsedSD1=sd[2];
            jLabelSdcard1Value.setText(UsedSD1+"/"+TotalSD1);
        }else{
            jLabelSdcard1Value.setText("");
        }
        //Memory
        BufferedReader memory=runCmd(Ram);
        while ((linebyline = memory.readLine()) != null) {
                    if (linebyline.contains("Total PSS:")) {out=linebyline;}
        }
        if(out.length()>10&&out.length()<22)        jLabelRAMvalue.setText(out.substring(10));
        else     jLabelRAMvalue.setText("");
        
        }
        
//        System.out.print(devices.length);
//        System.out.print("\n isBootLoader="+devices[0].isBootLoader());
//        System.out.print("\n isEmulator="+devices[0].isEmulator());
//        System.out.print("\n isOffline="+devices[0].isOffline());
//        System.out.print("\n isOnline="+devices[0].isOnline());
////        System.out.print("\n getProperties="+devices[0].getProperties());
//        System.out.print("\n getSerialNumber="+devices[0].getSerialNumber());
//        System.out.print("\n getClients="+devices[0].getClient(null));
//        System.out.print("\n getState="+devices[0].getState());
//        Map<String, String> properties = devices[0].getProperties();
//        System.out.print("\n size:"+properties.size());
//        Client[] clients = devices[0].getClients();
//        System.out.print("clients len:"+clients.length);
//        for(int i=0;i<clients.length;i++)
//        {
//        System.out.print("\nClient"+i+":"+clients[i]);
//        }
//            //Get Map in Set interface to get key and value
//        Set s=properties.entrySet();
//        //Move next key and value of Map by iterator
//        Iterator it=s.iterator();
//        while(it.hasNext())
//        {
//            // key=value separator this by Map.Entry to get key and value
//            Map.Entry m =(Map.Entry)it.next();
//            // getKey is used to get key of Map
//            String key=(String)m.getKey();
//            // getValue is used to get value of key in Map
//            String value=(String)m.getValue();
//            System.out.println(key+"\t\t\t :"+value);
//           // System.exit(0);
//        }
//        System.out.println("ro.build.version.release:"+properties.get("ro.build.version.release"));
//        System.out.println("dhcp.wlan0.gateway:"+properties.get("dhcp.wlan0.gateway"));
//        System.out.println("dhcp.wlan0.server:"+properties.get("dhcp.wlan0.server"));
//        System.out.println("dhcp.wlan0.mask:"+properties.get("dhcp.wlan0.mask"));
//        System.out.println("dhcp.wlan0.dns1:"+properties.get("dhcp.wlan0.dns1"));
//        System.out.println("dhcp.wlan0.ipaddress:"+properties.get("dhcp.wlan0.ipaddress"));
//        System.out.println("net.dns1:"+properties.get("net.dns1"));
//        System.out.println("net.dns2:"+properties.get("net.dns2"));
//        System.out.println("persist.radio.nitz_sons_0_0:"+properties.get("persist.radio.nitz_sons_0_0"));
//        System.out.println("persist.sys.theme:"+properties.get("persist.sys.theme"));
//        System.out.println("persist.sys.timezone:"+properties.get("persist.sys.timezone"));
//        System.out.println("ro.build.date:"+properties.get("ro.build.date"));
//        System.out.println("ro.sf.lcd_density:"+properties.get("ro.sf.lcd_density"));
//        System.out.println("ro.product.model:"+properties.get("ro.product.model"));
//        System.out.println("ro.product.manufacturer:"+properties.get("ro.product.manufacturer"));
//        System.out.println("ro.build.version.codename:"+properties.get("ro.build.version.codename"));
//        System.out.println("ro.nova.rom_info:"+properties.get("ro.nova.rom_info"));
//        System.out.println("ro.config.ringtone:"+properties.get("ro.config.ringtone"));
//        System.out.println("wifi.supplicant_scan_interval:"+properties.get("wifi.supplicant_scan_interval"));
//        System.out.println("gsm.operator.alpha:"+properties.get("gsm.operator.alpha"));
//        System.out.println("wlan.driver.config:"+properties.get("wlan.driver.config"));
//        System.out.println(":"+properties.get(""));
      

    }
    public static BufferedReader runCmd(String input){
        String[] cc = input.split(" ");
        BufferedReader inStreamReader=null;
        try {
                String line = "";
                ProcessBuilder pb = new ProcessBuilder(cc);
                pb.redirectErrorStream(true);
                Process process = pb.start();
                inStreamReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                
            } catch (IOException ex) {}
        return inStreamReader;
    }
}
